Ext.require([
    'Ext.form.field.ComboBox',
    'Ext.form.FieldSet',
    'Ext.tip.QuickTipManager',
    'Ext.toolbar.Paging',
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.state.*'
]);
Ext.onReady(function() {
	var cbstore = new Ext.data.Store({
		singleton:true,
        autoDestroy:true,
        fields: ["projectName", "id"],
        proxy:{
            type:'ajax',
            url:jypath+'/estate/project/findProjectList?resourcesName=resName_group_list',
            reader:{
                type: 'json', 
                root: 'root'  // 数据
           }
        },
        autoLoad:true
	});
	
/*	var userList = null;
	$.ajax({
		type: "POST",
		url:jypath+'/marketing/salesGroupUser/findSystemUserList',
	  	dataType: "json",
	  	data:{
	  		isDataPermission:true
	  	},
     	async: false,
     	success: function(data){
    	 	userList=data.root;
     	}
 	});*/
	
	//系统用户
	var userStore = new Ext.data.Store({
		autoDestroy: true,
        fields: ["userName", "id"],
		proxy: {
				type: 'ajax',
		        url: jypath+'/marketing/salesGroupUser/findSystemUserList?isDataPermission=true',
		        reader: {   
			        type: 'json', 
			        root: 'root'
		        }
		},
        autoLoad: false/*
       	data:userList*/
	});
	  
	//项目组状态
	var statusStoreList = [
		{"value":"0","text":"正常"},
	  	{"value":"1","text":"已关闭"}
	];
	var statusStore = Ext.data.Store({
		autoDestroy: true,
  		fields :["value","text"],
        data : statusStoreList
    });
	    
	//组员状态
	var userStatusStoreList = [
	   	{"value":"0","text":"正常"},
	   	{"value":"1","text":"已移除"}
	];
	var userStatusStore = Ext.data.Store({
		autoDestroy: true,
	 	fields :["value","text"],
	 	data : userStatusStoreList
	});
	    
	//是否具备项目属性
	var saleAttrStore = [
    	{"value":"0","text":"否"},
    	{"value":"1","text":"是"}
    ];
	var saleAttrStore = Ext.data.Store({
		autoDestroy: true,
	  	fields :["value","text"],
	 	data : saleAttrStore
	});
	  
	  
	var form = new Ext.form.FormPanel({
		title : "项目组信息",
		anchor :'90%',
		height : 200,
		frame : true,
		renderTo : Ext.getBody(),  // 渲染到页面
		items:[
			{
				xtype:'combobox',
	    	   	fieldLabel:'所属项目',
	    	   	store:cbstore,
	    	   	displayField: "projectName",
	    	   	valueField:"id",
	    	   	id:'cbstore',
	    	   	blankText: "所属项目不能为空!",
		    	allowBlank: false,
	    	   	listeners:{
		    		render: function(c) {  
		    			c.getStore().on("load", function(s, r, o) {
		    				if(salesGroupList!=null&&salesGroupList!=""){
		    					var resultObj=JSON.parse(salesGroupList);
		    					c.setValue(resultObj.projectId);
		    				}
		    			});
		    		}
		    	}
			},{
		   		fieldLabel: "项目组名称",
		    	name:'groupName',
		    	xtype:'textfield',
		    	id:'saleGroupName',
		    	blankText: "项目组名称不能为空!",
		    	allowBlank: false
			},{
		    	xtype:'combobox',
				fieldLabel:'项目组状态',
		    	store:statusStore,
		    	displayField: "text",
		    	valueField:"value",
		    	id:'statusInput',
		    	blankText: "项目组状态不能为空!",
		    	allowBlank: false
			}
			/*
			 * 是否管理组去掉,2016-8-19_JHSong
			,{
	       		xtype: "fieldcontainer",
	       		layout: "hbox",
	       		items: [
					{
		   				xtype:'combobox',
			    	   	fieldLabel:'是否管理组',
			    	   	store:saleAttrStore,
			    	   	displayField: "text",
			    	   	valueField:"value",
			    	   	selectOnFocus: true,
			    	   	id:'saleAttrInput',
			    	   	blankText: "是否管理组",
		    			allowBlank: false,
			    	   	listeners: {
			     			afterRender: function(combo) {
				        　　			Ext.getCmp('saleAttrInput').setValue("0");
				       		}
				 		}
					},
			 		{
						xtype: "displayfield",
			    	 	value: "（注：\“财务\”等非销售人员专用组，请选择【是】，以避免影响相关数据查询）"
			    	 }
		    	]
			}
			*/,{
		   		xtype:'numberfield',
		    	fieldLabel:'排序编号',
		    	id:'sortInput'
			}
		]
	});
	
	Ext.QuickTips.init();
	var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
 		clicksToEdit: 1
    });
    
    var store = Ext.create('Ext.data.Store', {
        fields: ["userId","status","userCN"],
        remoteSort: false,
        proxy: {
     		type: 'ajax',
            url: jypath+'/marketing/salesGroupUser/list?salesGroupId='+salesGroupId,
            reader: {   
                type: 'json', 
                root: 'rows',  
                totalProperty: 'total' 
            }
        },
        autoLoad: false  // 即时加载数据
    });
    
    if(salesGroupList != null && salesGroupList != ""){
		var resultObj = JSON.parse(salesGroupList);
		Ext.getCmp("saleGroupName").setValue(resultObj.name);
		Ext.getCmp("statusInput").setValue(resultObj.status);
		//Ext.getCmp("saleAttrInput").setValue(resultObj.saleAttr);
		Ext.getCmp("sortInput").setValue(resultObj.sort);
	}
    
	var grid = Ext.create('Ext.grid.Panel', {
  		store: store,
        columnLines: true,
        columns: [{
     		text: '员工',
            sortable : false,
            width:320,
            dataIndex: 'userId',
            editor:new Ext.form.field.ComboBox({
         		queryMode:'local',
              	id:'userId',
              	valueField:'id',
              	displayField:'userName',
              	store:userStore
            }),  
            renderer: function(value,metadata,record){  
                var index = userStore.find('id',value);  
                if(index!=-1){  
                    return userStore.getAt(index).data.userName;  
                }else{
                	return record.data.userCN;
                }  
            }
        },{
      		text: '组员状态', 
     		dataIndex: 'status',
            editor: new Ext.form.field.ComboBox({
         		queryMode:'local',
              	id:'userStatus',
              	valueField:'value',
              	displayField:'text',
              	store:userStatusStore
    		}),
            renderer: function(value,metadata,record){
            	var valueText = "";
            	if(value=="0"){
            		valueText="正常";
            	}else if(value=="1"){
            		valueText="已移除";
            	}
            	return valueText;
            }
        }
//	        ,{
//	        	text:'操作',
//	        	xtype : 'actioncolumn',
//	        	items:[{
//	        		 icon :  jypath+'/resources/ExtJSicons/book_delete.png',
//	        		 handler: function(grid, rowIndex, colIndex) {
//	        			 grid.getStore().removeAt(rowIndex);
//	        		 }
//	        	}]
//	        }
        ],
        selModel: {
            selType: 'rowmodel'
        },
        autoHeight: true,
        title: '项目组成员',
        renderTo: Ext.getBody(),
        viewConfig: {
            stripeRows: true
        },
        plugins: [cellEditing],
        dockedItems: [{
     		xtype: 'toolbar',
            dock: 'bottom',
            ui: 'footer',
            layout: {
                pack: 'center'
            },
            items: [{
                minWidth: 80,
                text: '保存',
                handler:groupBatch
            },{
                minWidth: 80,
                text: '返回',
                handler:backProjectDetail
            }]
        }],
        tbar:[
      		{text:'新增',icon:jypath+'/resources/ExtJSicons/book_add.png',handler:showAlert},"-"
     	]
    });
	    
    var descPanel = Ext.create('Ext.panel.Panel', {
		frame : true,
		renderTo: Ext.getBody(),
    	items: {
    		xtype: "displayfield",
    	 	value: "（注: 状态为\"已移除\"的员工将失去相应项目、客户权限）"
    	}
    });
	function showAlert (){
		Ext.define('Record', { 
	  		extend: 'Ext.data.Model',
	  		fields: ["userId","status"]
	    });
	    var record  = new Record({
	    	userId: "",
	    	status: "0"
	    });
	    grid.getStore().insert(0, record);
	    cellEditing.startEditByPosition({
	        row: 0, 
	    	column: 0
	    });
	}

	//批量保存	    
	function groupBatch(){
		var jsonArray=[];
		var records=store.getCount();
		if(records<=0){
			Ext.Msg.alert('提示', '请新增项目组成员！');
			return;
		}
		for(var i=0;i<records;i++){
			var row=store.getAt(i).data;
			if(row.userId && row.status){
				jsonArray.push(Ext.JSON.encode(row));
			}
		}
		if(jsonArray.length<=0){
			Ext.Msg.alert('提示', '请新增项目组成员！');
			return;
		}
		var resultJson=Ext.JSON.encode(jsonArray); //单元格数据
		
		var formValid = form.getForm();
	    if(formValid.isValid()){
		    //提交数据
			Ext.Ajax.request({
				url: jypath+'/marketing/salesGroupUser/add',
				params: { 
					id: salesGroupId,
					projectId:Ext.getCmp('cbstore').getValue(),
					name:Ext.getCmp("saleGroupName").getValue(),
					status:Ext.getCmp("statusInput").getValue(),
					//saleAttr:Ext.getCmp("saleAttrInput").getValue(),
					sort:Ext.getCmp("sortInput").getValue(),
					batchJson:resultJson
				},
				callback: function (options, success, response) {
					if (success) {
						var obj = JSON.parse(response.responseText);
						if(obj.res=="1"){
							Ext.MessageBox.confirm("提示","保存成功,是否继续操作?",function(btn,txt){
								if(btn=="no"){
									if(salesGroupId!=null&&salesGroupId!=""){
										parent.TabControlRemove("addGroup"+salesGroupId);
									}else{
										parent.TabControlRemove("addGroup");
									}
								}
							});
						}else{
							Ext.MessageBox.alert("系统提示",obj.resMsg); 
						}
		      		}else{
		        		Ext.MessageBox.alert("系统提示","系统异常!");
		        	}
				}
			});
	    }
	}

	function backProjectDetail(){
		if(salesGroupId!=null&&salesGroupId!=""){
			parent.TabControlRemove("addGroup"+salesGroupId);
		}else{
			parent.TabControlRemove("addGroup");
		}
	}
	
	function initAgent(){
		Ext.define('Record', { 
			extend: 'Ext.data.Model',
			fields: ["userId","status"]
		}); 
		for(var i=0;i<10;i++){
		    var record  = new Record({
		    	userId: "",
		    	status: "0"
		    });
			grid.getStore().insert(i, record);
		}
		cellEditing.startEditByPosition({
		    row: 0, 
			column: 0
		});
	}

	if(null!=salesGroupId && salesGroupId!=""){
		userStore.load({
			callback:function(){
			   store.load();
			}
		});
		
	}else{
		userStore.load();
		initAgent();
	}
});

